import json, os, pathlib, logging

from protolib import get_app_root

from widgets.file_browser import FileBrowserWidget

logger = logging.getLogger(__name__)

def load_config(file_browser: FileBrowserWidget):
    os.makedirs(pathlib.Path(get_app_root(), 'config'), exist_ok=True)
    os.makedirs(pathlib.Path(get_app_root(), 'config', 'typing'), exist_ok=True)

    path = pathlib.Path(get_app_root(), 'config', 'typing', 'types.json')
    if os.path.exists(path):
        with open(path) as f:
            file_browser.config['typing']['types'] = json.load(f)
            f.close()
    else:
        with open(path, 'w') as f:
            json.dump(file_browser.config['typing']['types'], f)
            f.close()

    path = pathlib.Path(get_app_root(), 'config', 'typing', 'mimetypes.json')
    if os.path.exists(path):
        with open(path) as f:
            file_browser.config['typing']['mimetypes'] = json.load(f)
            f.close()
    else:
        with open(path, 'w') as f:
            json.dump(file_browser.config['typing']['mimetypes'], f)
            f.close()

    logger.info('Loaded config')

def dump_config(file_browser: FileBrowserWidget):
    os.makedirs(pathlib.Path(get_app_root(), 'config'), exist_ok=True)
    os.makedirs(pathlib.Path(get_app_root(), 'config', 'typing'), exist_ok=True)

    path = pathlib.Path(get_app_root(), 'config', 'typing', 'types.json')
    with open(path, 'w') as f:
        json.dump(file_browser.config['typing']['types'], f)
        f.close()

    path = pathlib.Path(get_app_root(), 'config', 'typing', 'mimetypes.json')
    with open(path, 'w') as f:
        json.dump(file_browser.config['typing']['mimetypes'], f)
        f.close()

    logger.info('Dumped config')
